//
//  UploadManagerEngine.m
//  Growth
//
//  Created by 洪波 陈 on 5/29/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "UploadManagerEngine.h"

#import "PublicMethodEngine.h"
#import "UploadManagerDatabaseEngine.h"
#import "WebRequest.h"

#import "SDDataCache.h"
#import "Photo.h"
#import "CJSONDeserializer.h"
#import "CJSONSerializer.h"

static UploadManagerEngine *_shareEngine = nil;

@implementation UploadManagerEngine

@synthesize uploadState;
@synthesize albumUploadState;

+ (UploadManagerEngine *)sharedUploadManagerEngine{
	if (!_shareEngine) {
		_shareEngine = [[UploadManagerEngine alloc] init];
		_shareEngine.uploadState = kUploadStateWaiting;
        _shareEngine.albumUploadState = kAlbumUploadStateAllow;
	}
	
	return _shareEngine;
}

#pragma mark - 后台上传唤醒方式
//网络变更唤醒
- (void)networkStateChanged:(NetworkStatus)status
{
    //  NotReachable = 0,
    //	ReachableViaWiFi,
    //	ReachableViaWWAN
    switch (status) {
        case NotReachable:
        {
            //停止上传线程
            
            break;
        }
        case ReachableViaWiFi:
        {
            //如果只允许Wifi上传，则可开启上传
            [self localDataCheck];
            
            break;
        }
        case ReachableViaWWAN:
        {
            //如果3G下不允许上传，则暂停上传
            [self localDataCheck];
            break;
        }
        default:
            break;
    }
}


//新的记录数据唤醒
- (void)newRecordAction
{
    CLog(@"new record need upload!");
    
    [self localDataCheck];
}

//新的宝宝生活数据
- (void)newLifeAction
{
    CLog(@"new life data need upload!");
    [self localDataCheck];
}



//新的大事件数据
- (void)newAnniversaryAction{
    
    CLog(@"new Anniversary need upload");
    [self localDataCheck];
    
}

//新相册记录唤醒
- (void)newAlbumAction{
    
    CLog(@"new Album need upload");
    [self localDataCheck];
    
}

#pragma mark - Local data upload check, 检查本地数据
static int uploadType = kUploadTypeNone;
static int uploadId = 0;
static int uploadCount = 0;

- (void)localDataCheck
{
    NetworkEngine *networkEngine = [NetworkEngine sharedNetworkEngine];
    NetworkStatus networkStatus = networkEngine.hostNetworkStatus;
    CLog(@"localDataCheck 1");
    
    //正在上传，忙碌状态
    if (_shareEngine.uploadState == kUploadStateBusy) {
        CLog(@"localDataCheck uploadState %d", _shareEngine.uploadState);
        
        return;
    }
    
    //当同一条记录上传超出5次时说明上传已经出现问题，跳出上传，等待下次触发
    if (uploadCount >5) {
        uploadType = kUploadTypeNone;
        uploadId = 0;
        uploadCount = 0;
        
        //上传状态为等待
        _shareEngine.uploadState = kUploadStateWaiting;
        
        return;
    }
    
    CLog(@"localDataCheck 2");
    switch (networkStatus) {
        case NotReachable:
        {
            CLog(@"localDataCheck 3");
            //无网络什么都用做喽
            break;
        }
        case ReachableViaWWAN:
        {
            CLog(@"localDataCheck 4");
            //检测Record本地记录
            BOOL isWork = [self recordTryUpload]; 
            if (isWork) {
                break;
            }
            
            //检测Record本地记录
            isWork = [self lifeTryUpload]; 
            if (isWork) {
                break;
            } 
            
            //检查大事件本地记录
            isWork = [self anniversaryTryUpload];
            if (isWork) {
                break;
            } 
            
            CLog(@"localDataCheck 5");
            if (ALBUM_UPLOAD_IS_3G) {
                //如果使用3G上传相册,需要检测相册
                isWork = [self albumTryUpload];
                if (isWork) {
                    break;
                }
            }
            
            //如果没有上传将upload标记清空
            if (!isWork) {
                uploadType = kUploadTypeNone;
                uploadId = 0;
                uploadCount = 0;
            }
            
            CLog(@"localDataCheck 6");
            break;
        }
        case ReachableViaWiFi:
        {
            CLog(@"localDataCheck 7");
            //检测Record本地记录
            BOOL isWork = [self recordTryUpload]; 
            if (isWork) {
                break;
            } 
            
            //检测Record本地记录
            isWork = [self lifeTryUpload]; 
            if (isWork) {
                break;
            } 
            
            //检查大事件本地记录
            isWork = [self anniversaryTryUpload];
            if (isWork) {
                break;
            } 

            
            //检测相册数据
            CLog(@"localDataCheck 8");
            isWork = [self albumTryUpload];
            if (isWork) {
                break;
            }
            CLog(@"localDataCheck 9");
            
            //如果没有上传将upload标记清空
            if (!isWork) {
                uploadType = kUploadTypeNone;
                uploadId = 0;
                uploadCount = 0;
            }
            
            break;
        }
        default:
            break;
    }
    
}

#pragma mark - Record Upload
- (BOOL)recordTryUpload
{
    
    CLog(@"recordTryUpload 1");
    if (_shareEngine.uploadState == kUploadStateBusy) {
        return YES; 
    }
    else {
        CLog(@"recordTryUpload 2");
        NSString *sql = [NSString stringWithFormat:@"select min(id) as id from LocalRecord"];
        
        NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
        
        CLog(@"recordTryUpload 3");
        
        NSString *recordId = [dict objectForKey:@"id"];
        CLog(@"recordId %@", recordId);
        
        if (recordId != nil) {
            CLog(@"recordTryUpload 4");
            [self recordUpload];
            CLog(@"recordTryUpload 5");
            
            //判断是否是同一个类型、同一个id多次上传
            if (uploadType == kUploadTypeRecord && uploadId == [recordId intValue]) {
                uploadCount++;
            }
            else {
                uploadType = kUploadTypeRecord;
                uploadId = [recordId intValue];
                uploadCount = 0;
            }
            
            return YES;
        }
        else {
            return NO;
        }
    }
}

- (void)recordUpload
{
    CLog(@"recordUpload 1");
    
    NSString *sql = [NSString stringWithFormat:@"select min(id) as id from LocalRecord"];
    
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
    
    NSString *recordId = [dict objectForKey:@"id"];
    CLog(@"recordId %@", recordId);
    
    CLog(@"recordUpload 2");
    
    if (recordId != nil) {
        
        CLog(@"recordUpload 3");
        
        _shareEngine.uploadState = kUploadStateBusy;
        
        sleep(0.5);
        
        CLog(@"recordUpload 4");
        
        [NSThread detachNewThreadSelector:@selector(recordUploadThread:) toTarget:self withObject:recordId];
        
        CLog(@"recordUpload 5");
    }
    else {
        _shareEngine.uploadState = kUploadStateWaiting;
        //[self recordTryUpload];
        [self localDataCheck];
    }
    
}

- (void)recordUploadThread:(NSString *)recordId
{
    CLog(@"recordUploadThread begine");
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    CLog(@"bgein");
    NSString *sql = [NSString stringWithFormat:@"select id, json, url, uid, tid,time from LocalRecord where id = %@", recordId];
    
    NSArray *keyValue = [NSArray arrayWithObjects:@"id", @"json", @"url", @"uid", @"tid", @"time", nil];
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:keyValue];
    
    NSString *jsonString = [dict objectForKey:@"json"];
    
    CLog(@"local jsonString %@", jsonString); 
    
     NSData *dat = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
    NSError *error = nil;
   
    NSMutableDictionary  *jsonDict = [[NSMutableDictionary alloc] initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:dat error:&error]];
     
    NSString *imageUrlKey = [NSString stringWithFormat:@"%@",[dict objectForKey:@"time"]]  ;
    NSData *imageData =   [[SDDataCache sharedDataCache:kImageCache_Locale_Record] dataFromKey:imageUrlKey];
    
     NSString *imageString = @"null";
    if (imageData) {
       
        imageString=[Photo NSData2String:imageData];
        
         [jsonDict setObject:imageString forKey:@"fileData"] ; 
    }

    CLog(@"UPLOAD STR %@", jsonDict);
    
    NSString *dataStr = [[CJSONSerializer serializer] serializeDictionary:jsonDict];
    
    CLog(@"UPLOAD STR %@", dataStr);
    
    NSData *jsonData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [WebRequest diaryCreateRequestWith:jsonData];        
    CLog(@"request %@", request);
    
    [jsonDict release];
    
    NSError *err=nil;
    NSURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:&response 
                                                           error:&err];
    int statusCode = -1;
    if (response) {
        NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
        statusCode = [httpResponse  statusCode ];
    }

    if(statusCode != 200)
    {
        NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        CLog(@"returnData %@", string);
        CLog(@"Upload error ");
        //if([err code])
        if (err) {
            CLog(@"Code:%d,domain:%@,localizedDesc:%@",[err code],
                 [err domain],[err localizedDescription]);
        }
    }
    else
    {

        NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        CLog(@"returnData %@", string);
        
        @try {
            NSInteger returnId = [string intValue];
            
            if (returnId >0) {
                
                CLog(@"uopload record success");
                
                NSInteger databaseId = [[dict objectForKey:@"id"] intValue];
                
                NSString *sql = [NSString stringWithFormat:@"delete from LocalRecord where id = %d", databaseId];
                
                BOOL isDelete = NO;
                int deleteCount = 0;
                while (!isDelete && deleteCount <2) {
                    isDelete = [[UploadManagerDatabaseEngine sharedDatabaseEngine] executeSQL:sql];
                    [[SDDataCache sharedDataCache:kImageCache_Locale_Record] removeDataForKey:[dict objectForKey:@"time"]];
                    
                    deleteCount++;
                }
                
                if (!isDelete) {
                    CLog(@"删除进入死循环，应该是不可能的！");
                }
            }
            
        }
        @catch (NSException *exception) {
            CLog(@"Upload error return data error");
        }
        @finally {
            
        }
        
        [string release];
        
    }
    
    //[self recordUpload];
    self.uploadState = kUploadStateWaiting;
    [self localDataCheck];
    
    CLog(@"End record");
    
    [pool release]; 
}


#pragma mark - Album Upload

- (BOOL)albumTryUpload
{
    CLog(@"albumTryUpload");
    if (_shareEngine.uploadState == kUploadStateBusy) {
        return YES; 
    }
    else if(_shareEngine.albumUploadState == kAlbumUploadStateAllow){
        NSString *sql = @"select min(id) as id from locale_album";
        NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
        
        NSString *albumId = [dict objectForKey:@"id"];
        CLog(@"albumid %@", albumId);
        
        if (albumId != nil) {
            [self albumUpload];
            
            
            //判断是否是同一个类型、同一个id多次上传
            if (uploadType == kUploadTypeAlbum && uploadId == [albumId intValue]) {
                uploadCount++;
            }
            else {
                uploadType = kUploadTypeAlbum;
                uploadId = [albumId intValue];
                uploadCount = 0;
            }
            
            return YES;
        }
        else {
            //已经没有待上传相册数据
            [[SDDataCache sharedDataCache:kImageCache_Locale_Album] clearDisk]; 
            return NO;
        }
    }
    else {
        return NO;
    }
}

- (void)albumUpload
{
    
    NSString *sql = [NSString stringWithFormat:@"select min(id) as id from locale_album"];
    
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
    
    NSString *albumId = [dict objectForKey:@"id"];
    CLog(@"albumid %@", albumId);
    
    if (albumId != nil) {
        _shareEngine.uploadState = kUploadStateBusy;
        
        sleep(0.5);
        
        [NSThread detachNewThreadSelector:@selector(albumUploadThread:) toTarget:self withObject:albumId];
    }
    else {
        _shareEngine.uploadState = kUploadStateWaiting;
        //[self albumTryUpload];
        [self localDataCheck];
    }
    
}


- (void)albumUploadThread:(NSString *)albumId
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    CLog(@"albumUploadThread bgein");
    
    NSString *sql = [NSString stringWithFormat:@"select id, locale_url, photo_month, photo_year, photo_date,uid, tid from locale_album where id=%@", albumId] ;
    
    NSArray *keyValue = [NSArray arrayWithObjects:@"id", @"locale_url", @"photo_month", @"photo_year", @"photo_date", @"uid", @"tid", nil];
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:keyValue];
    
    CLog(@"upload locale id %d", [[dict objectForKey:@"id"] intValue]);
    
    NSString *urlStr = [dict objectForKey:@"locale_url"];
    NSString *photoDateStr = [dict objectForKey:@"photo_date"];
    NSDate *photoDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:photoDateStr];
    
    
    NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"tid", @"photoData", @"photoName", @"photoDate", nil];
    
    NSString *tidStr = [dict objectForKey:@"tid"];
    NSString *uidStr = [dict objectForKey:@"uid"];
    NSString *photoName = @"hobo.png";
    
    
    NSDate *zoneDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
    NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
    
    NSTimeInterval time = [photoDate timeIntervalSince1970];
    long long int date = (long long int)(time -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
    NSNumber *photoDateNum = [NSNumber numberWithLongLong:date];
    
    NSData *imageData = [[SDDataCache sharedDataCache:kImageCache_Locale_Album] dataFromKey:urlStr];
    
    
    NSString *photoData = [Photo NSData2String:imageData];
    if (photoData == nil) {
        photoData = @"";
    }
    
    NSArray *valueArray = [NSArray arrayWithObjects:uidStr, tidStr, photoData, photoName, photoDateNum, nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];;
    
    NSMutableURLRequest *requestUpload = [WebRequest albumUploadWith:jsonData];
    
    CLog(@"request %@", requestUpload);
    
    NSError *err=nil;
    NSURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:requestUpload
                                               returningResponse:&response 
                                                           error:&err];
    
    int statusCode = -1;
    if (response) {
        NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
        statusCode = [httpResponse  statusCode ];
    }
    
    if(statusCode != 200)
    {
        CLog(@"Upload error ");
        //if([err code])
        if (err) {
            CLog(@"Code:%d,domain:%@,localizedDesc:%@",[err code],
                 [err domain],[err localizedDescription]);
        }
    }
    else
    {
        NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        CLog(@"returnData %@", string);
        
        @try {
            NSInteger returnId = [string intValue];
            
            if (returnId >0) {
                CLog(@"uopload record success");
                
                NSInteger databaseId = [[dict objectForKey:@"id"] intValue];
                
                NSString *sql = [NSString stringWithFormat:@"delete from locale_album where id = %d", databaseId];
                
                BOOL isDelete = NO;
                int deleteCount = 0;
                while (!isDelete && deleteCount <2) {
                    isDelete = [[UploadManagerDatabaseEngine sharedDatabaseEngine] executeSQL:sql];
                    
                    [[SDDataCache sharedDataCache:kImageCache_Locale_Album] removeDataForKey:urlStr];
                    
                    deleteCount++;
                }
                
                if (!isDelete) {
                    CLog(@"删除进入死循环，应该是不可能的！");
                }
                
                CLog(@"returnData %@", returnData);
            }
            
        }
        @catch (NSException *exception) {
            CLog(@"Upload error return data error");
        }
        @finally {
            
        }
        
        [string release];
        
    }
    

    
    //[self albumUpload];
    self.uploadState = kUploadStateWaiting;
    [self localDataCheck];
    CLog(@"End Album");
    
    [pool release];    
    
    
}


#pragma mark - 宝宝生活
- (BOOL)lifeTryUpload
{
    CLog(@"lifeTryUpload 1");
    if (_shareEngine.uploadState == kUploadStateBusy) {
        return YES; 
    }
    else {
        CLog(@"lifeTryUpload 2");
        NSString *sql = [NSString stringWithFormat:@"select min(id) as id from locale_life"];
        
        NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
        
        CLog(@"lifeTryUpload 3");
        
        NSString *foodId = [dict objectForKey:@"id"];
        CLog(@"foodid %@", foodId);
        
        if (foodId != nil) {
            CLog(@"lifeTryUpload 4");
            [self lifeUpload];
            CLog(@"lifeTryUpload 5");
            
            
            //判断是否是同一个类型、同一个id多次上传
            if (uploadType == kUploadTypeLife && uploadId == [foodId intValue]) {
                uploadCount++;
            }
            else {
                uploadType = kUploadTypeLife;
                uploadId = [foodId intValue];
                uploadCount = 0;
            }
            
            
            return YES;
        }
        else {
            return NO;
        }
    }
}

- (void)lifeUpload
{
    CLog(@"lifeUpload 1");
    
    NSString *sql = [NSString stringWithFormat:@"select min(id) as id from locale_life"];
    
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
    
    NSString *foodId = [dict objectForKey:@"id"];
    CLog(@"foodId %@", foodId);
    
    CLog(@"lifeUpload 2");
    
    if (foodId != nil) {
        
        CLog(@"lifeUpload 3");
        
        _shareEngine.uploadState = kUploadStateBusy;
        
        sleep(0.5);
        
        CLog(@"lifeUpload 4");
        
        [NSThread detachNewThreadSelector:@selector(lifeUploadThread:) toTarget:self withObject:foodId];
        
        CLog(@"lifeUpload 5");
    }
    else {
        _shareEngine.uploadState = kUploadStateWaiting;
        [self localDataCheck];
    }
    
}

- (void)lifeUploadThread:(NSString *)foodId
{
    CLog(@"lifeUploadThread begine");
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    CLog(@"bgein");
    NSString *sql = [NSString stringWithFormat:@"select id, json, url, uid, tid,time from locale_life where id = %@", foodId];
    
    NSArray *keyValue = [NSArray arrayWithObjects:@"id", @"json", @"url", @"uid", @"tid", @"time", nil];
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:keyValue];
    
    NSString *jsonString = [dict objectForKey:@"json"];
    
    CLog(@"local jsonString %@", jsonString); 
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [WebRequest createActivityRequestWith:jsonData];        
    CLog(@"request %@", request);
    
    NSError *err=nil;
    NSURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:&response 
                                                           error:&err];
    
    int statusCode = -1;
    if (response) {
        NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
        statusCode = [httpResponse  statusCode ];
    }
    
    if(statusCode != 200)
    {
        CLog(@"Upload error ");
        //if([err code])
        if (err) {
            CLog(@"Code:%d,domain:%@,localizedDesc:%@",[err code],
                 [err domain],[err localizedDescription]);
        }
        
    }
    else
    {
        
        
        NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        CLog(@"returnData %@", string);
        
        @try {
            NSInteger returnId = [string intValue];
            
            if (returnId >0) {
                
                CLog(@"uopload record success");
                
                NSInteger databaseId = [[dict objectForKey:@"id"] intValue];
                
                NSString *sql = [NSString stringWithFormat:@"delete from locale_life where id = %d", databaseId];
                
                BOOL isDelete = NO;
                int deleteCount = 0;
                while (!isDelete && deleteCount <2) {
                    isDelete = [[UploadManagerDatabaseEngine sharedDatabaseEngine] executeSQL:sql];
                    
                    deleteCount++;
                }
                
                if (!isDelete) {
                    CLog(@"删除进入死循环，应该是不可能的！");
                }
                
                CLog(@"returnData %@", returnData);
            }
            
        }
        @catch (NSException *exception) {
            CLog(@"Upload error return data error");
        }
        @finally {
            
        }
        
        [string release];
        
    }

    
    self.uploadState = kUploadStateWaiting;
    [self localDataCheck];
    
    CLog(@"End life");
    
    [pool release];
}


#pragma mark 大事件

- (BOOL)anniversaryTryUpload
{
    CLog(@"anniversaryTryUpload 1");
    if (_shareEngine.uploadState == kUploadStateBusy) {
        return YES; 
    }
    else {
        CLog(@"anniversaryTryUpload 2");
        NSString *sql = [NSString stringWithFormat:@"select min(id) as id from local_anniversary"];
        
        NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
        
        CLog(@"anniversaryTryUpload 3");
        
        NSString *annId = [dict objectForKey:@"id"];
        CLog(@"annId %@", annId);
        
        if (annId != nil) {
            CLog(@"anniversaryTryUpload 4");
            [self anniversaryUpload];
            CLog(@"anniversaryTryUpload 5");
            
            //判断是否是同一个类型、同一个id多次上传
            if (uploadType == kUploadTypeAnniversary && uploadId == [annId intValue]) {
                uploadCount++;
            }
            else {
                uploadType = kUploadTypeAnniversary;
                uploadId = [annId intValue];
                uploadCount = 0;
            }
            
            return YES;
        }
        else {
            return NO;
        }
    }
}

- (void)anniversaryUpload
{
    CLog(@"anniversaryTryUpload 1");
    
    NSString *sql = [NSString stringWithFormat:@"select min(id) as id from local_anniversary"];
    
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:[NSArray arrayWithObjects:@"id", nil]];
    
    NSString *annId = [dict objectForKey:@"id"];
    CLog(@"annId %@", annId);
    
    CLog(@"local_anniversary 2");
    
    if (annId != nil) {
        
        CLog(@"local_anniversary 3");
        
        _shareEngine.uploadState = kUploadStateBusy;
        
        sleep(0.5);
        
        CLog(@"local_anniversary 4");
        
        [NSThread detachNewThreadSelector:@selector(anniversaryUploadThread:) toTarget:self withObject:annId];
        
        CLog(@"lifeUpload 5");
    }
    else {
        _shareEngine.uploadState = kUploadStateWaiting;
        [self localDataCheck];
    }
    
}

- (void)anniversaryUploadThread:(NSString *)foodId
{
    CLog(@"anniversaryUploadThread begine");
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    CLog(@"bgein");
    NSString *sql = [NSString stringWithFormat:@"select id, json, url, uid, tid,time from local_anniversary where id = %@", foodId];
    
    NSArray *keyValue = [NSArray arrayWithObjects:@"id", @"json", @"url", @"uid", @"tid", @"time", nil];
    NSDictionary *dict = [[UploadManagerDatabaseEngine sharedDatabaseEngine] selectOneWithSQL:sql select:keyValue];
    
    NSString *jsonString = [dict objectForKey:@"json"];
    
    CLog(@"local jsonString %@", jsonString); 
    
    NSData *dat = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    
    NSMutableDictionary  *jsonDict = [[NSMutableDictionary alloc] initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:dat error:&error]];
    
    NSString *imageUrlKey = [NSString stringWithFormat:@"%@",[dict objectForKey:@"time"]]  ;
    NSData *imageData =   [[SDDataCache sharedDataCache:kImageCache_Locale_Record] dataFromKey:imageUrlKey];
    
    NSString *imageString = @"null";
    if (imageData) {
        
        imageString=[Photo NSData2String:imageData];
        
        [jsonDict setObject:imageString forKey:@"fileData"] ; 
    }
        
    
    NSString *dataStr = [[CJSONSerializer serializer] serializeDictionary:jsonDict];
    
    NSData *jsonData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [WebRequest createActivityRequestWith:jsonData];        
    CLog(@"request %@", request);
    
    [jsonDict release];
    
    NSError *err=nil;
    NSURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:&response 
                                                           error:&err];
    
    int statusCode = -1;
    if (response) {
        NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
        statusCode = [httpResponse  statusCode ];
    }
    
    if(statusCode != 200)
    {
        CLog(@"Upload error ");
        //if([err code])
        if (err) {
            CLog(@"Code:%d,domain:%@,localizedDesc:%@",[err code],
                 [err domain],[err localizedDescription]);
        }
        
    }
    else
    { 
        NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
        CLog(@"returnData %@", string);
        
        @try {
            NSInteger returnId = [string intValue];
            
            if (returnId >0) {
                CLog(@"uopload record success");
                
                NSInteger databaseId = [[dict objectForKey:@"id"] intValue];
                
                NSString *sql = [NSString stringWithFormat:@"delete from local_anniversary where id = %d", databaseId];
                
                BOOL isDelete = NO;
                int deleteCount = 0;
                while (!isDelete && deleteCount <2) {
                    isDelete = [[UploadManagerDatabaseEngine sharedDatabaseEngine] executeSQL:sql];
                    [[SDDataCache sharedDataCache:kImageCache_Locale_Record] removeDataForKey:[dict objectForKey:@"time"]];
                    
                    deleteCount++;
                }
                
                if (!isDelete) {
                    CLog(@"删除进入死循环，应该是不可能的！");
                }
            }
            
        }
        @catch (NSException *exception) {
            CLog(@"Upload error return data error");
        }
        @finally {
            
        }
        
        [string release];
        
    }
    
    self.uploadState = kUploadStateWaiting;
    [self localDataCheck];
    
    CLog(@"End local_anniversary");
    
    [pool release];
}


@end
